// 获取本机ip
const getIpAddress = function () {
  var interfaces = require('os').networkInterfaces();
  for (var devName in interfaces) {
    var iface = interfaces[devName];
    for (var i = 0; i < iface.length; i++) {
      var alias = iface[i];
      if (alias.family === 'IPv4' && alias.address !== '127.0.0.1' && !alias.internal) {
        return alias.address;
      }
    }
  }
};

//打开默认浏览器
const openDefaultBrowser = function (url) {
  var exec = require('child_process').exec;
  console.log(`process.platform: ${process.platform}`);
  switch (process.platform) {
    case "darwin":
      exec('open ' + url);
      break;
    case "win32":
      exec('start ' + url);
      break;
    default:
      exec('xdg-open', [url]);
  }
};

// 变量
const Koa = require('koa');
const app = new Koa();
const static = require('koa-static');
const proxy = require('koa-proxies');

const ip = getIpAddress();
const port = 8081;
const host = ip + ':' + port;
const pathName = '/index.html';
const url = 'http://' + host + pathName;

// 静态文件托管
app.use(static('./'));

// OSS静态资源反向代理
// app.use(proxy(['/favicon.ico', '/asset', '/tmp'], {
//   target: 'https://ylmtst.mao-app.com',
//   headers: { // 确保headers里面所有的key全部小写
//     host: 'ylmtst.mao-app.com',
//     referer: 'https://ylmtst.mao-app.com/test.html'
//   },
//   changeOrigin: true
// }));

// // api请求反向代理
// app.use(proxy('/api', {
//   target: 'https://dev.mao-app.com',
//   headers: { // 确保headers里面所有的key全部小写
//     host: 'ylmtst.mao-app.com',
//     referer: 'https://ylmtst.mao-app.com/test.html'
//   },
//   changeOrigin: true,
//   rewrite: path => path.replace(/^\/api/, '')
// }));

// // WebSocket反向代理
// app.use(proxy('/chatService')).listen(8020).on("upgrade", (req, res) => {
//   proxy.proxy.ws(req, res, {
//     target: 'wss://wstst.mao-app.com',
//     ws: true,
//     changeOrigin: true
//   });
// });

// 监听端口
app.listen(port, () => {
  console.log(`server started at ${host}`);
  console.log(`Auto open page ${url} in default brower`);
  openDefaultBrowser(url);
});